package com.kxxnzstdsw.schedule

import com.kxxnzstdsw.schedule.job.BasicJob
import org.koin.core.Koin
import org.quartz.Scheduler
import org.reflections.Reflections
import org.reflections.scanners.Scanners


fun Scheduler.scan(koin: Koin, scan: String?) {
  (scan ?: "com").let { prefix ->
    Reflections(prefix, Scanners.TypesAnnotated)
      .getTypesAnnotatedWith(ScheduleJob::class.java)
      .forEach {
        val scheduleJob = (koin.get(it.kotlin) as BasicJob)
        val job = scheduleJob.job
        val trigger = scheduleJob.trigger
        if (this.checkExists(job.key)) {
          this.deleteJob(job.key)
          this.addJob(job, false,true)
        } else {
          this.addJob(job, false,true)
        }
        if (this.checkExists(trigger.key)) {
          this.unscheduleJob(trigger.key)
          this.scheduleJob(trigger)
        } else {
          this.scheduleJob(trigger)
        }
      }
  }
}
